<template>
  <div class="video-container">
    <div class="video-controls">
      <h2>视频流：MP4</h2>
      <BackButton />
    </div>
    <canvas ref="videoCanvas" class="video-frame"></canvas>
  </div>
</template>

<script>
import BackButton from '../components/BackButton.vue'

export default {
  name: 'videoViewMp4',
  components:{
    BackButton
  },
  data() {
    return {
      ws: null,
    };
  },
  mounted() {
    this.connect();
  },
  beforeUnmount() {
    this.disconnect();
  },
  beforeRouteLeave(to, from, next) {
    this.disconnect();
    next()
  },
  methods: {
    connect() {
      this.ws = new WebSocket('ws://127.0.0.1:8098/video/input');
      
      this.ws.binaryType = 'arraybuffer';
      
      this.ws.onopen = () => {
        console.log('WebSocket connected');
      };
      
      this.ws.onmessage = (event) => {
        if (event.data instanceof ArrayBuffer) {
          this.displayVideoFrame(event.data);
        }
      };
      
      this.ws.onerror = (error) => {
        console.error('WebSocket error:', error);
      };
      
      this.ws.onclose = () => {
        console.log('WebSocket disconnected');
      };
    },
    disconnect() {
      if (this.ws) {
        this.ws.close();
      }
    },
    displayVideoFrame(arrayBuffer) {
      const blob = new Blob([arrayBuffer], { type: 'image/jpeg' });
      const url = URL.createObjectURL(blob);
      
      const img = new Image();
      img.onload = () => {
        const canvas = this.$refs.videoCanvas;
        const ctx = canvas.getContext('2d');
        
        // 设置canvas尺寸与图像匹配
        canvas.width = img.width;
        canvas.height = img.height;
        
        ctx.drawImage(img, 0, 0);
        URL.revokeObjectURL(url);
      };
      img.src = url;
    }
  }
};
</script>

<style scoped>
.video-container {
  width: 90%;
  margin: 20px;
  text-align: center;
}

.video-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 20px;
}

.video-frame {
  width: 100%;
  max-width: 100%;
  max-height: 80vh;
  aspect-ratio: 16/9; /* 保持16:9比例 */
  background-color: #000;
  border: 1px solid #ddd;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
</style>